# admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.utils.translation import gettext_lazy as _
from .models import User
from django.utils.html import format_html

class UserAdmin(BaseUserAdmin):
    # 调整列表页显示的字段
    list_display = ('username', 'name', 'phone_number',  'role', 'is_staff', 'is_active')
    
    # 调整过滤器
    list_filter = ('is_active', 'role')
    
    # 自定义字段集合，这里定义了添加和修改用户时表单字段的顺序
    fieldsets = (
        (None, {'fields': ('username', 'password_display')}),
        (_('个人信息'), {'fields': ('name', 'phone_number', 'email')}),
        (_('用户权限'), {'fields': ('role', 'is_active', 'is_staff', 'is_superuser')}),
        (_('重要日期'), {'fields': ('last_login', 'date_joined')}),
    )
    
    # 添加用户时的表单字段顺序
    # add_fieldsets = (
    #     (None, {
    #         'classes': ('wide',),
    #         'fields': ('username', 'password1', 'password2','name', 'phone_number',  'role', ),
    #     }),
    # )
        # 新增用户时的表单字段 - 关键修改在这里
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'name', 'phone_number', 'email'),
        }),
        (_('密码设置'), {
            'classes': ('wide',),
            'fields': ('password1', 'password2'),
            'description': _('密码至少8位，不能与用户信息过于相似，不能是常见密码。')
        }),
        (_('用户权限'), {
            'classes': ('wide',),
            'fields': ('role', 'is_active', 'is_staff', 'is_superuser'),
        }),
    )
    # 搜索字段
    search_fields = ('username', 'name', 'phone_number', 'email')
    ordering = ('username',)
    readonly_fields = ('password_display',)  # 添加自定义只读字段
    
    def password_display(self, obj):
        """自定义密码字段的显示"""
        if not obj.pk:
            return '-'
        
        change_password_url = f'/admin/api/user/{obj.pk}/password/'
        return format_html(
            '<div class="custom-password-field">'
            '<span class="password-masked">密码已设置</span> '
        '<a href="{}" style="background-color: white; color: black; border: 1px solid #ccc; padding: 6px 12px; text-decoration: none; border-radius: 4px; display: inline-block; font-size: 13px;">修改密码</a>'
            '</div>',
            change_password_url
        )
    password_display.short_description = '密码'
    


# 注册自定义User模型和UserAdmin
admin.site.register(User, UserAdmin)
